package com.firebird.app.kotlin.stock.trend.utils

import android.graphics.drawable.Drawable
import android.os.Handler
import android.os.Message
import java.io.IOException
import java.io.InputStream
import java.lang.ref.SoftReference
import java.net.MalformedURLException
import java.net.URL
import java.util.*


/**
 * 异步加载并缓存图片的工具类
 * @author ljk
 * @date   2019年11月8日
 */
class SimpleAsyncImageLoader {
    private val imageCache: HashMap<String?, SoftReference<Drawable>?>
    fun loadDrawable(imgUrl: String?, callback: ImageCallback): Drawable? {
        if (imageCache.containsKey(imgUrl)) { //判断内存缓存中是否有该图片，有就直接返回图片
            val softReference = imageCache[imgUrl]
            val drawable = softReference!!.get()
            if (drawable != null) {
                return drawable
            }
        }
        val handler: Handler = object : Handler() {
            override fun handleMessage(msg: Message) {
                callback.imageLoaded(imgUrl, msg.obj as Drawable)
            }
        }
        object : Thread() {
            override fun run() {
                val drawable = loadImageFromUrl(imgUrl)
                imageCache[imgUrl] = SoftReference(drawable)
                val msg = handler.obtainMessage(0, drawable)
                handler.sendMessage(msg)
            }
        }.start()
        return null
    }

    interface ImageCallback {
        fun imageLoaded(imgUrl: String?, drawable: Drawable?)
    }

    companion object {
        /**
         * 通过网络加载图片
         * @param url    图片地址
         * @return
         */
        fun loadImageFromUrl(url: String?): Drawable {
            val m: URL
            var `is`: InputStream? = null
            try {
                m = URL(url)
                `is` = m.content as InputStream
            } catch (e: MalformedURLException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return Drawable.createFromStream(`is`, "src")
        }
    }

    init {
        imageCache = HashMap()
    }
}
